package nrpc.message;

import java.lang.reflect.Type;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.util.function.Consumer;

import message.AbstractMessageBuilder;
import message.MessageBuilder;
import message.reflect.HandlerMapper;
import nrpc.message.meta.ReturnMessage;

public class ReturnMessageBuilder extends AbstractMessageBuilder{

	public ReturnMessageBuilder(Consumer<? super Object> callback, HandlerMapper mapper, Type type) {
		super(callback);
		this.build = new ReturnMessage();
		builder = mapper.getBuilderSupplier(type).get((x)->{
			((ReturnMessage)build).obj = x;
		});
	}

	private MessageBuilder builder;
	private int step;
	
	@Override
	public boolean read(ByteBuffer byteBuffer) {
		switch(step){
		case 0:
			try {
				((ReturnMessage)this.build).label = byteBuffer.getInt();
			} catch (BufferUnderflowException e) {
				return false;
			}
			step++;
		case 1:
			if(!(builder.read(byteBuffer))) return false;
			step++;
		}
		return super.read(byteBuffer);
	}

}
